<?php
//define ('ROOT_PATH', '/var/www/hrm');
//require_once (ROOT_PATH. '/lib/confs/ldapConf.php');

class CustomLDAP{ 
/**
     * Custom code, add LDAP user account
     
    public function addLdapUser($userId,$password){
    	
    
    	$ldapconn = ldap_connect ( LDAPConf::$ldap_host, LDAPConf::$ldap_port );
    	if ($ldapconn) {
    			
    		// Sets the protocol version of the LDAP Server
    		$tested = @ldap_set_option ( $ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3 );
 
    			
    		if ($tested) {
    			@ldap_bind ( $ldapconn, LDAPConf::$ldap_root_user, LDAPConf::$ldap_root_password);
    			$user_record = $this->getHrmInfoForLDAP($userId,$password);
				
    			//for debug
    			
    			//
    			
    			$user_dn = 'uid=' . $user_record['uid'] . ',' . LDAPConf::$ldap_usersDN ;
    			$r = ldap_add($ldapconn,$user_dn , $user_record);
    			
    			ldap_unbind ( $ldapconn );
    			ldap_close($ldapconn);
    		}
    	}
    	
    }
 * */
 
    /*

    
    public function modifiedLdapUser($userId) {
		$ldapconn = ldap_connect ( LDAPConf::$ldap_host, LDAPConf::$ldap_port );
		if ($ldapconn) {
			
			// Sets the protocol version of the LDAP Server
			$tested = @ldap_set_option ( $ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3 );
			
			if ($tested) {
				@ldap_bind ( $ldapconn, LDAPConf::$ldap_root_user, LDAPConf::$ldap_root_password );
				$user_record = $this->getHrmInfoForLDAP ( $userId , NULL);
				
				// for debug
				
				//
				
				$user_dn = 'uid=' . $user_record ['uid'] . ',' . LDAPConf::$ldap_usersDN;
				$r = ldap_modify( $ldapconn, $user_dn, $user_record );
				
				ldap_unbind ( $ldapconn );
				ldap_close ( $ldapconn );
			}
		}
	}
    */
    
/**
 * 
 */
    public function userOnGroupFilter($username,$gidNumber){
        return '(&('. LDAPConf::$ldap_login_attr.'='.$username. ')(' . LDAPConf::$ldap_group_id_attr . '=' . $gidNumber . '))' ;
    }
    
    /**
     * 
     */
    public function syncAllLdapUsers(){
        $filter = '&( (objectClass=' . LDAPConf::$ldap_user_objectClass . ')(gidNumber=' . LDAPConf::LDAP_EMPLOYEE_GID_NUMBER . '))' ;
        $user_records = $this->ldapSearch($filter);
        if ($user_records ) {
                
              foreach ($user_records  as $user_record) {
                  $this->syncLdapUser($user_record[LDAPConf::$ldap_login_attr][0]);
              }      
        }
    }
    

	/**
	 * Sync when User login HRM 
	 * @param  $userId
	 * return boolean
	 */
	public function syncLdapUser($username){
	/*	
		$systemUserService = new SystemUserService();
		$systemUser = $systemUserService->getSystemUser($userId);
		
		$username = $systemUser->getUserName();
		*/

		
		$query = Doctrine_Query::create ()->from ( 'SystemUser' )->where ( 'user_name = ?', $username );
		if ($query->fetchOne ()) {
			return $this->saveHrmUserFromLDAP($username, true);	
		}
		else {
			if (LDAPConf::$ldap_create_hrm_user){
				return $this->saveHrmUserFromLDAP($username, false);
			}
			return FALSE;
			
		}
/*		
		$ldapconn = ldap_connect ( LDAPConf::$ldap_host, LDAPConf::$ldap_port );
		
		
		$systemUsers = Doctrine::getTable('SystemUser')->createQuery('u')
		->where('u.deleted=?', 0)->execute();
	
		foreach ($systemUsers as $systemUser){
		//	$this->writeDebug($systemUser->getUserName());
			$userId = $systemUser->getId();
			$this->modifiedLdapUser($userId);
			
		}
*/
	}
	/**
	 * 
	 * @param unknown $username
	 * @param unknown $edited
	 * @return Ambigous <boolean, number>|boolean
	 */
	public function saveHrmUserFromLDAP($username, $edited){
         
                $filter= $this->userOnGroupFilter($username, LDAPConf::LDAP_EMPLOYEE_GID_NUMBER);
				$result = $this->ldapSearch($filter);
				
				// add HRM User from LDAP entry
				
				if ($result) {
				
				//	$result = @ldap_get_entries ( $ldapconn, $search_result );
					if ($result [0]) {
						$user_record = $result[0];
						$saveSuccess = $this->saveHrmUser($user_record, $edited);
						
						return $saveSuccess ;
					}
					
				}
				
			return FALSE;
	}
	
	/**
	 * 
	 */
	public function saveHrmUser ($user_record, $edited ){
		
		$username = $user_record[LDAPConf::$ldap_login_attr][0];
	//	var_dump($username);
	//	var_dump($edited);
		$systemUserService = new SystemUserService();
		
		if ($edited == false){
			//var_dump($user_record['uid'][0]);
			$user = new SystemUser();
			$user->setDateEntered(date('Y-m-d H:i:s'));
			 $user -> setUserRoleId(2); // 2 mean ESS
		}
		else {
			//var_dump($user_record['uid']);
			$query = Doctrine_Query::create ()->from ( 'SystemUser' )->where ( 'user_name = ?', $username);
			$result = $query->fetchOne();
			if ($result){
				$userId = $result->getId();
				$user = $systemUserService->getSystemUser($userId);
			//	var_dump( "affaf");
				if (!($user instanceof SystemUser) ) return FALSE;
				
				$user->setDateModified(date('Y-m-d H:i:s'));
			} 
			
		}
		

	
	   // Sync employee Information
        $employeeId = $user_record[LDAPConf::$ldap_employee_id_attr][0];
        
        $employeeService = new EmployeeService();
        $employeeService -> setEmployeeDao(new EmployeeDao());
        /*
        $query = Doctrine_Query:: create()->from('Employee e')
                            ->where('e.employee_id = ?', $employeeId);
        $employee = $query->fetchOne();               
          */
        $employee = $employeeService->getEmployeeByEmployeeId($employeeId);                    
        
        if (is_null($employee) || !$employee) {
            $employee = new Employee();
            $employee->setEmployeeId($employeeId);
            
        }
        $employee -> setFirstName($user_record[LDAPConf::$ldap_firstname_attr][0]);
        $employee -> setLastName($user_record[LDAPConf::$ldap_lastname_attr][0]);
        $savedEmployee = $employeeService->saveEmployee($employee);
        
        if ($employee instanceof Employee){
              $empNumber = $employee->getEmpNumber();     
        
       
            // Sync System User
              $user -> setDeleted(0);
             
		// $empData = $this->getValue('employeeName');
		      $user->setEmpNumber($empNumber); //set employee number ; LDAPConf::$ldap_employee_number_attr
		      $user->setUserName($username); //set employee username
		      $user->setStatus(1); //1 mean enabled
		//var_dump($user->getUserName());
		      $savedUser = $systemUserService->saveSystemUser($user, false);
		// var_dump($savedUser);
		      if ($savedUser instanceof SystemUser)
		      {
			
			     return $savedUser->getId();
		      } 
	
		      else return false;
        }
        else return false;	
	}
	/**
	 * 
	 *
	 * @param string $filter
	 * @return string
	 */
	public function ldapSearch($filter){
		$ldapconn = ldap_connect ( LDAPConf::$ldap_host, LDAPConf::$ldap_port );
		if ($ldapconn) {
		
			// Sets the protocol version of the LDAP Server
			$tested = @ldap_set_option ( $ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3 );
			@ldap_set_option ( $ldapconn, LDAP_OPT_REFERRALS, 0 );
		
			if ($tested) {
		         @ldap_bind ( $ldapconn, LDAPConf::$ldap_root_user, LDAPConf::$ldap_root_password );
				$search_result = @ldap_search ( $ldapconn, LDAPConf::$ldap_baseDN, $filter );
		
				// verify user and password
		
				if ($search_result) {
		
					$result = @ldap_get_entries ( $ldapconn, $search_result );
					return $result ;
				}
			}
			ldap_close ( $ldapconn );
		}
		
		
		return false;
	//	ldap_close ( $ldapconn );
	}
    public function getHrmInfoForLDAP($userId, $password = NULL){

    	$systemUserService = new SystemUserService();
    	$systemUser = $systemUserService->getSystemUser($userId);
    //	$this->writeDebug(var_export($systemUser,true));
    	
    	$user_record['objectclass'][0]= "top";
    	$user_record['objectclass'][1]= "person";
    	$user_record['objectclass'][2]= "inetOrgPerson";
    	$user_record['objectclass'][3]= "posixAccount";
    	
    	$user_record['cn'] = $systemUser->getEmployee()->getFullName();
    	$user_record['uid'] = $systemUser->getUserName(); 
    	$user_record['sn']= $systemUser->getEmployee()->getLastName() ;
    	$user_record['givenName']= $systemUser->getEmployee()->getFirstName();
    	$user_record['homeDirectory']="/home/" . $user_record['uid'];
    	$user_record['uidNumber']= $userId;
    	$user_record['gidNumber']= "1000";
    	
    	if ($password !=NULL){
    		$user_record['userPassword']= $password;
    	}
    	    	

    	
    	return $user_record;
    	
    }

	public function checkToken($token){
		$filter = '(x-authenticationKey=' . $token .')' ;
		$result = $this->ldapSearch($filter);
		if ($result){
			if ($result[0]){
				$user = $result[0];
				$username = $user[LDAPConf::$ldap_login_attr][0];
				return $username ;
			}
		}
		return false;
		
	}
    public function writeDebug($stringData){
    	$myFile = "/home/hoangtuan/LVTN/lvtn2/hrm/symfony/plugins/customLDAP/hrm.log";
    	$fh = fopen($myFile, 'w') or die("can't open file");

    	fwrite($fh, $stringData);

    	fclose($fh);
    }
}




 
